import type * as VueRouter from 'vue-router';
import _ from 'lodash';

import router, { ROOT_ROUTE_NAME, getSubAppExceptionRoutes } from '@core/utils/router';

const viewRouteModules = import.meta.glob<{ default: VueRouter.RouteRecordRaw }>(
  '../views/*/routes.*',
  { eager: true },
);
const migrateMetaToProps = (routeRecord: VueRouter.RouteRecordRaw): VueRouter.RouteRecordRaw => {
  const mergedRoute = routeRecord;
  const props = typeof routeRecord.props === 'boolean' ? {} : routeRecord.props;
  const mergedProps = { ...props, fromMeta: routeRecord.meta };
  if (!_.isEmpty(mergedProps)) {
    mergedRoute.props = props;
  }
  if (!_.isEmpty(routeRecord.children)) {
    mergedRoute.children = mergedRoute.children?.map(migrateMetaToProps);
  }
  return mergedRoute;
};
const viewRoutes: VueRouter.RouteRecordRaw[] = [];
for (const modulePath of Object.keys(viewRouteModules)) {
  viewRoutes.push(migrateMetaToProps(viewRouteModules[modulePath].default));
}
viewRoutes.push(getSubAppExceptionRoutes());

router.addRoute({
  path: '/',
  name: ROOT_ROUTE_NAME,
  redirect: '/user/list',
  children: viewRoutes,
});

export default router;
